<template>
  <van-field
    v-model="value"
    :name="params.value"
    :label="params.label"
    :placeholder="params.placeholder || '请选择'"
    is-link
    readonly
    v-bind="{ ...params.bind }"
    @click="openPicker"
  />
  <van-popup v-model:show="showPicker" position="bottom">
    <van-date-picker
      v-bind="{ ...params.bind }"
      v-model="currentDate"
      @confirm="getDatePickerData"
      @cancel="showPicker = false"
    />
  </van-popup>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import regexFunctions from '@/utils/regex.js'

const showPicker = ref(false)
// 校验并返回第一个错误
const validateByRegex = (input, regex) => {
  let flag = ''
  for (const element of regex) {
    if (!regexFunctions[element.regFun](input)) {
      flag = element.msg
      break
    }
  }
  return flag
}
const props = defineProps(['params', 'modelValue', 'formParams'])
const value = ref(props.modelValue)
const currentDate = ref([props.modelValue])
const openPicker = () => {
  !props.params.refuseEvent && (showPicker.value = true)
  currentDate.value =
    typeof value.value === 'string' ? [value.value] : value.value
}
const emits = defineEmits(['update:modelValue', 'validate', 'getText'])

const getDatePickerData = data => {
  if (value.value && props.params.event) {
    props.params.event.funcName()
  }

  value.value = data && data.selectedValues.join('')
  showPicker.value = false
  // change触发时 向父组件返回值 并将数据校验暴露出来
  data && emits('update:modelValue', data && data.selectedValues.join(''))
  if (props.params.regex) {
    // 校验数据是否符合规则
    const res = validateByRegex(
      data && data.selectedValues.join(''),
      props.params.regex,
    )
    emits('validate', {
      name: props.params.value,
      validateRes: res === '',
      validateMsg: res,
    })
  }
}

onMounted(() => {
  getDatePickerData()
})

watch(
  () => props.modelValue,
  newVal => {
    value.value = newVal
  },
)
</script>
